package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.login.TsLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    /**
     * 微信支付
     * @param paymentType
     * @param orderNo
     * @return
     */
    @TsLogin
    @Operation(summary = "微信支付")
    @PostMapping("/createJsapi/{paymentType}/{orderNo}")
    public Result createJsapi(@PathVariable String paymentType, @PathVariable String orderNo) {
        log.info("订单号：" + orderNo);
        //获取用户Id
        Long userId = AuthContextHolder.getUserId();
        //调用服务层方法
        Map<String, Object> result = wxPayService.createJsapi(paymentType, orderNo, userId);
        //返回数据
        return Result.ok(result);
    }

    /**
     *  查询微信支付状态
     * @param orderNo
     * @return
     */
    @Operation(summary = "查询微信支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable String orderNo) {
        //调用服务层方法
        Transaction result = wxPayService.queryPayStatus(orderNo);
        //  判断result
        if (null != result && Transaction.TradeStateEnum.SUCCESS.equals(result.getTradeState())){
            //  说明支付成功！修改交易记录状态，订单状态.
            paymentInfoService.updatePaymentStatus(result);
            //  封装一个map
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("msg","支付成功");
            //  返回数据
            return Result.ok(hashMap);
        }
        //  返回数据
        return Result.ok(false);
    }

}
